# apps/audit/models.py
from django.db import models
from django.contrib.auth import get_user_model
from apps.tenants.models import Tenant

User = get_user_model()

class AuditLog(models.Model):
    """
    审计日志
    """
    ACTION_CHOICES = [
        ('create', '创建'),
        ('update', '更新'),
        ('delete', '删除'),
        ('login', '登录'),
        ('logout', '登出'),
        ('import', '导入'),
        ('export', '导出'),
    ]

    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name="用户")
    username = models.CharField(max_length=150, verbose_name="用户名")  # 快照，避免用户删除后丢失
    action = models.CharField(max_length=20, choices=ACTION_CHOICES, verbose_name="操作")
    model_name = models.CharField(max_length=100, verbose_name="模型")
    object_id = models.IntegerField(null=True, blank=True, verbose_name="对象ID")
    object_repr = models.CharField(max_length=200, verbose_name="对象描述")
    changes = models.JSONField(null=True, blank=True, verbose_name="变更内容")
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name="IP地址")
    user_agent = models.TextField(null=True, blank=True, verbose_name="User Agent")
    timestamp = models.DateTimeField(auto_now_add=True, verbose_name="时间")
    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, db_index=True, verbose_name="租户")

    def __str__(self):
        return self.name

    def __str__(self):
        return f"{self.username} {self.get_action_display()} {self.object_repr}"